#include <stdio.h>
#include <stdlib.h>
#include <sys/syslog.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <syslog.h>

void usr1(int sig)
{
	if (setpgid(0, 0) < 0) {
		perror("setpgid");
	}
	return;
}

void usr2(int sig)
{
	printf("pid=%d recv %s\n", getpid(), strsignal(sig));
	if (setsid() < 0) {
		perror("setsid");
	}
	return;
}

int main1()
{
	pid_t pid1, pid2, pid3;
	printf("parent pid=%d, gid=%d sid=%d\n", getpid(), getpgrp(), getsid(getpid()));
	signal(SIGUSR1, usr1);
	signal(SIGUSR2, usr2);

	if ((pid1 = fork()) == 0) {
		for (;;) {
			printf("child 1 pid=%d, gid=%d sid=%d\n", getpid(), getpgrp(), getsid(getpid()));
			pause();
		}
	}

	if ((pid2 = fork()) == 0) {
		for (;;) {
			printf("child 2 pid=%d, gid=%d sid=%d\n", getpid(), getpgrp(), getsid(getpid()));
			pause();
		}
	}

	if ((pid3 = fork()) == 0) {
		for (;;) {
			if (setsid() < 0) {
				perror("setsid");
			}
			printf("child 3 pid=%d, gid=%d sid=%d\n", getpid(), getpgrp(), getsid(getpid()));
			pause();
		}
	}
	for (;;) {
		pause();
	}

	return 0;
}

void sig(int sig)
{
	syslog(LOG_INFO | LOG_LOCAL0, "%d %s", sig, strsignal(sig));
}

int main()
{
	syslog(LOG_INFO | LOG_LOCAL0, "%s", "START");
	signal(SIGTSTP, sig);
	signal(SIGCONT, sig);
	signal(SIGTTIN, sig);
	char buf[1024];
	int len = read(STDIN_FILENO, buf, sizeof(buf));
	// if (fork() == 0) {
	// 	for (;;) {
	// 		int len = read(STDIN_FILENO, buf, sizeof(buf));
	// 		buf[len] = 0;
	// 		write(STDOUT_FILENO, buf, len);
	// 	}
	// }
	// for (;;) {
	// 	int len = read(STDIN_FILENO, buf, sizeof(buf));
	// 	buf[len] = 0;
	// 	write(STDOUT_FILENO, buf, len);
	// }
	return 0;
}